<template>
  <div class="summarizeby">
    <span>{{$t('custom.component.columns.measure')}}</span>
    <el-popover ref="summarizebyForm"
                placement="bottom"
                width="280"
                @after-leave="handleLeaveSummarizeAddPopover"
                style="z-index:2019;display:block;float:right"
                trigger="manual"
                v-model="addVisible">

      <el-form ref="summarizebyElForm"
               :rules="summarizebyFormRules"
               :model="newSummarizeBy"
               class="groupby-popover">
        <div>
          <div style="display: flex;align-items: center;justify-content: space-between;height:32px;"
               v-if="!newSummarizeBy.advanced">
            <span style="font-weight:bold;font-size: 16px;">{{$t('custom.component.columns.measure')}}</span>
            <el-button style="float:right;font-size:12px;"
                       type="text"
                       @click="newAdvance(newSummarizeBy.advanced)">{{$t('custom.component.columns.advance')}}</el-button>
          </div>
          <div style="display: flex;align-items: center;justify-content: end;height:32px;"
               v-if="newSummarizeBy.advanced">
            <i class="cuifont icon_chevron_lift"
               style="font-size:10px;padding-right:10px;"
               @click="advancedChange(newSummarizeBy.advanced)"></i>
            <span style="font-weight:bold;font-size: 16px;">{{$t('custom.component.columns.advance')}}</span>
          </div>
        </div>
        <el-divider></el-divider>
        <el-form-item :label="$t('custom.component.columns.calculatemeasure')"
                      prop="fx"
                      v-if="newSummarizeBy.advanced">
          <el-input type="textarea"
                    :rows="3"
                    placeholder=""
                    v-model="newSummarizeBy.fx">
          </el-input>
          <div style="display: flex;align-items: center;justify-content: end;margin-bottom:-10px;">
            <i class="cuifont icon_info"
               style="color:#E6A23C;padding-right:5px;"></i>
            <span style="font-size:10px;color:#E6A23C;margin-right:5px;">{{$t('custom.component.columns.calculatemeasurefx')}}</span>
          </div>
        </el-form-item>
        <el-form-item :label="$t('custom.component.columns.summarizeType')"
                      prop="func"
                      v-if="!newSummarizeBy.advanced"
                      style="margin-top:10px;">
          <el-select v-model="newSummarizeBy.func"
                     @change="newChange"
                     style="width: 100%;"
                     :placeholder="$t('custom.component.columns.pleaseselect')">
            <el-option v-for="item in summarizeList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="newSummarizeBy.func === 'string_agg'&&!newSummarizeBy.advanced"
                      :label="$t('custom.component.columns.separator')"
                      prop="separator">
          <el-input v-model="newSummarizeBy.separator"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.component.columns.fields')"
                      prop="field"
                      v-if="!newSummarizeBy.advanced">
          <el-select v-model="newSummarizeBy.field"
                     @change="newChange"
                     style="width: 100%;"
                     :placeholder="$t('custom.component.columns.pleaseselect')">
            <el-option v-for="(item,index) in columnList"
                       :key="index"
                       :label="item.alias"
                       :disabled="newSummarizeBy.func === 'string_agg'&& item.dbType !== 'text'"
                       :value="item.columnName">
              <DataTypeIcon :dataTypeObj="{type:item.businessType,value:item.alias}"></DataTypeIcon>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('custom.component.columns.alias')"
                      prop="alias">
          <el-input v-model="newSummarizeBy.alias"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.component.columns.formatType')">
          <el-select class="formatType"
                     style="float:left"
                     @change="editSummarizeChange"
                     v-model="newSummarizeBy.businessType"
                     :placeholder="$t('custom.component.columns.pleaseselect')">
            <el-option v-for="item in formatTypeList"
                       :key="item.id"
                       :label="item.dictLabel"
                       :value="item.dictValue">
              <span>
                <i :class="`cuifont ${item.subjectCode}`"></i>
              </span>
              <span style="margin-left: 10px">{{ item.dictLabel }}</span>
            </el-option>
          </el-select>
          <el-popover ref="formatPopover"
                      placement="right-end"
                      width="430"
                      height="211"
                      @opened="openedHandler"
                      @show="addorEditFormatShow"
                      @hide="resetFormatType"
                      trigger="click"
                      style="z-index:2019;display:block;">
            <h3>{{$t('custom.component.columns.format')}}</h3>
            <NumberFormat ref="NumberFormat"
                          v-if="newSummarizeBy.businessType ==='number'"
                          :formatDataInfo="newSummarizeBy"></NumberFormat>
            <el-select v-model="newFieldsFormat"
                       v-else
                       clearable
                       filterable
                       default-first-option
                       :placeholder="$t('custom.component.columns.pleaseselect')"
                       style="width: 100%;">
              <el-option v-for="(its,index) in formatTypeItemList"
                         :key="index"
                         :label="its.dictLabel"
                         :value="its.dictValue"></el-option>
            </el-select>
            <div class="pop_title">{{$t('custom.component.columns.poptitle')}}</div>
            <div style="text-align: right; margin: 10px auto;">
              <el-button size="small"
                         @click="closeFormatPopover">{{ $t('custom.close') }}</el-button>
              <el-button size="small"
                         type="primary"
                         @click="saveFormatPopover">{{ $t('custom.save') }}</el-button>
            </div>
            <div slot="reference">
              <el-image fit="cover"
                        style="float:right;margin-top:5px"
                        :src="$ossLink+'/app/dashboard/format.png'"></el-image>
            </div>
          </el-popover>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="newSummarizeBy.distinct"  v-if="!newSummarizeBy.advanced">{{$t('custom.component.columns.distinct')}}</el-checkbox>
        </el-form-item>
      </el-form>
      <div style="text-align: right;">
        <el-button size="mini"
                   @click="handleCloseSummarizeAddPopover">{{$t('notice.close')}}</el-button>
        <el-button size="mini"
                   type="primary"
                   @click="addSummarizeby">{{$t('add')}}</el-button>
      </div>
      <i slot="reference"
         class="cuifont icon_add"
         style="float:right;margin-right:5px"
         @click="handleOpenSummarizeAddPopover"></i>
    </el-popover>
    <ul class="summarize-list">
      <li v-for="(item,index) in dataInfoCopy.measures"
          :key="index"
          :style="{backgroundColor:rowClass(item,index)}">{{item.alias}}
        <i class="el-icon-delete summarizeByDelete"
           @click="deleteSummarizeBy(index)"></i>
        <el-popover ref="editSummarizeByForm"
                    placement="top"
                    width="280"
                    @after-leave="handleLeaveSummarizeEditPopover"
                    trigger="manual"
                    v-model="item.editVisible"
                    style="z-index:2019;display:block;float:right">
          <el-form ref="editForm"
                   :rules="editFormRules"
                   :model="newSummarizeBy"
                   class="groupby-popover">
            <div>
              <div style="display: flex;align-items: center;justify-content: space-between;height:32px;"
                   v-if="!newSummarizeBy.advanced">
                <span style="font-weight:bold;font-size: 16px;">{{$t('custom.component.columns.measure')}}</span>
                <el-button style="float:right;font-size:12px;"
                           type="text"
                           @click="newAdvance(newSummarizeBy.advanced)">{{$t('custom.component.columns.advance')}}</el-button>
              </div>
              <div style="display: flex;align-items: center;justify-content: end;height:32px;"
                   v-if="newSummarizeBy.advanced">
                <i class="cuifont icon_chevron_lift"
                   style="font-size:10px;padding-right:10px;"
                   @click="advancedChange(newSummarizeBy.advanced)"></i>
                <span style="font-weight:bold;font-size: 16px;">{{$t('custom.component.columns.advance')}}</span>
              </div>
            </div>
            <el-divider></el-divider>
            <el-form-item :label="$t('custom.component.columns.calculatemeasure')"
                          prop="fx"
                          v-if="newSummarizeBy.advanced">
              <el-input type="textarea"
                        :rows="3"
                        placeholder=""
                        v-model="newSummarizeBy.fx">
              </el-input>
              <div style="display: flex;align-items: center;justify-content: end;margin-bottom:-10px;">
                <i class="cuifont icon_info"
                   style="color:#E6A23C;padding-right:5px;"></i>
                <span style="font-size:10px;color:#E6A23C;margin-right:5px;">{{$t('custom.component.columns.calculatemeasurefx')}}</span>
              </div>
            </el-form-item>
            <el-form-item :label="$t('custom.component.columns.summarizeType')"
                          prop="func"
                          v-if="!newSummarizeBy.advanced"
                          style="margin-top:10px;">
              <el-select v-model="newSummarizeBy.func"
                         @change="newChange"
                         :placeholder="$t('custom.component.columns.pleaseselect')">
                <el-option v-for="item in summarizeList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="newSummarizeBy.func === 'string_agg'&&!newSummarizeBy.advanced"
                          :label="$t('custom.component.columns.separator')"
                          prop="separator">
              <el-input v-model="newSummarizeBy.separator"></el-input>
            </el-form-item>
            <el-form-item :label="$t('custom.component.columns.fields')"
                          prop="field"
                          v-if="!newSummarizeBy.advanced">
              <el-select v-model="newSummarizeBy.field"
                         @change="newChange"
                         :placeholder="$t('custom.component.columns.pleaseselect')">
                <el-option v-for="(item,index) in columnList"
                           :key="index"
                           :label="item.alias"
                           :disabled="newSummarizeBy.func === 'string_agg'&& item.dbType !== 'text'"
                           :value="item.columnName">
                  <DataTypeIcon :dataTypeObj="{type:item.businessType,value:item.alias}"></DataTypeIcon>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('custom.component.columns.alias')"
                          prop="alias">

              <el-input v-model="newSummarizeBy.alias"></el-input>
            </el-form-item>
            <el-form-item :label="$t('custom.component.columns.formatType')">
              <el-select class="formatType"
                         style="float:left"
                         @change="editSummarizeChange"
                         v-model="newSummarizeBy.businessType"
                         :placeholder="$t('custom.component.columns.pleaseselect')">
                <el-option v-for="item in formatTypeList"
                           :key="item.id"
                           :label="item.dictLabel"
                           :value="item.dictValue">
                  <span>
                    <i :class="`cuifont ${item.subjectCode}`"></i>
                  </span>
                  <span style="margin-left: 10px">{{ item.dictLabel }}</span>
                </el-option>
              </el-select>
              <el-popover ref="editFormatPopover"
                          placement="right-end"
                          width="430"
                          height="211"
                          @opened="editOpenedHandler"
                          @hide="resetFormatType"
                          @show="editFormat"
                          trigger="click"
                          style="z-index:2019;display:block;">
                <h3>{{$t('custom.component.columns.format')}}</h3>
                <NumberFormat ref="NumberFormatEdit"
                              v-if="newSummarizeBy.businessType ==='number'"
                              :formatDataInfo="newSummarizeBy"></NumberFormat>
                <el-select v-model="newFieldsFormat"
                           v-else
                           clearable
                           filterable
                           default-first-option
                           :placeholder="$t('custom.component.columns.pleaseselect')"
                           style="width: 100%;">
                  <el-option v-for="(its,index) in formatTypeItemList"
                             :key="index"
                             :label="its.dictLabel"
                             :value="its.dictValue"></el-option>
                </el-select>
                <div class="pop_title">{{$t('custom.component.columns.poptitle')}}</div>
                <div style="text-align: right; margin: 10px auto;">
                  <el-button size="small"
                             @click="closeEditFormat">{{ $t('custom.close') }}</el-button>
                  <el-button size="small"
                             type="primary"
                             @click="saveEditFormatPopover">{{ $t('custom.save') }}</el-button>
                </div>
                <div slot="reference">
                  <el-image fit="cover"
                            style="float:right;margin-top:5px"
                            :src="$ossLink+'/app/dashboard/format.png'"></el-image>
                </div>
              </el-popover>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="newSummarizeBy.distinct"  v-if="!newSummarizeBy.advanced">{{$t('custom.component.columns.distinct')}}</el-checkbox>
            </el-form-item>
          </el-form>
          <div style="text-align: right; margin: 10px auto;">
            <el-button size="mini"
                       @click="handleCloseSummarizeEditPopover">{{$t('notice.close')}}</el-button>
            <el-button size="mini"
                       type="primary"
                       @click="confirmSummarizeby">{{$t('confirm')}}</el-button>
          </div>
          <i slot="reference"
             class="el-icon-edit summarizeByEidt"
             @click.stop="handleOpenSummarizeEditPopover(item,index)"
             style="float:right;line-height:35px;margin-right:10px"></i>
        </el-popover>
      </li>
    </ul>
  </div>
</template>
<script>
import DataTypeIcon from '@/components/script-render/components/data-type-icon'
import NumberFormat from '@/components/columns/columns-numberformat.vue'
import { isIncludeDot } from '@/utils/validate'
import invaildSql from '@/components/storybook/utilties/sql'
export default {
  components: { DataTypeIcon, NumberFormat },
  props: {
    // eslint-disable-next-line vue/no-dupe-keys
    dataInfoCopy: {
      type: Object,
      default: function () {
        return {}
      }
    },
    columnList: {
      type: Array,
      default: function () {
        return []
      }
    },
    errorFieldsList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    const validateFx = (rule, value, callback) => {
      if (invaildSql(value)) {
        callback(new Error('SQL security verification is not approved.'))
        return
      }
      callback()
    }

    var validateEdit = (rule, value, callback) => {
      if (!Array.isArray(this.dataInfoCopy.measures)) {
        this.dataInfoCopy.measures = []
      }
      let resIndex = ''
      let concatIndex = ''
      if (this.SummarizeByEditIndex.toString()) {
        resIndex = this.dataInfoCopy.measures.findIndex(item => {
          return item.alias === this.newSummarizeBy.alias
        })
      }
      if (this.GrounpByEditIndex.toString()) {
        resIndex = this.dataInfoCopy.dimensions.findIndex(item => {
          return item.alias === this.newGroupBy.alias
        })
      }
      concatIndex = this.dataInfoCopy.dimensions.concat(this.dataInfoCopy.measures).findIndex(item => {
        return (item.alias === this.newSummarizeBy.alias)
      })
      if (concatIndex !== -1 && ((this.SummarizeByEditIndex.toString() && resIndex !== this.SummarizeByEditIndex) || (this.GrounpByEditIndex.toString() && resIndex !== this.GrounpByEditIndex))) {
        return callback(new Error(this.$t('custom.component.columns.inputalias')))
      } else {
        callback()
      }
    }
    var validateAlias = (rule, value, callback) => {
      if (!Array.isArray(this.dataInfoCopy.measures)) {
        this.dataInfoCopy.measures = []
      }
      if (!Array.isArray(this.dataInfoCopy.dimensions)) {
        this.dataInfoCopy.dimensions = []
      }
      let isExist = this.dataInfoCopy.measures.concat(this.dataInfoCopy.dimensions).some(item => {
        return (item.alias === this.newSummarizeBy.alias)
      })
      if (isExist) {
        return callback(new Error(this.$t('custom.component.columns.inputalias')))
      } else {
        callback()
      }
    }
    return {
      // fieldsList: [],
      newSummarizeBy: {
        func: '',
        separator: '',
        alias: '',
        field: '',
        fieldAlias: '',
        businessType: '',
        fieldsFormat: '',
        fieldsNewFormat: {
          fieldsNewFormatType: 'number',
          decimals: 0,
          option: 'regular'
        },
        distinct: false,
        dbType: '',
        advanced: false,
        fx: '',
        editVisible: false,
        isNewPage: false
      },
      newGroupBy: {
        alias: '',
        field: '',
        fieldsFormat: ''
      },
      newFieldsFormat: '',
      SummarizeByEditIndex: '',
      GrounpByEditIndex: '',
      summarizebyFormRules: {
        func: [
          { required: true, message: this.$t('custom.component.columns.pleaseselect'), trigger: 'change' }
        ],
        separator: [
          { required: true, message: this.$t('custom.component.columns.inuptseparator'), trigger: 'change', pattern: '[^ \x22]+' }
        ],
        field: [
          { required: true, message: this.$t('custom.component.columns.pleaseselect'), trigger: 'change' }
        ],
        alias: [
          { required: true, message: this.$t('custom.component.columns.inputalias'), trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: validateAlias, trigger: 'blur' }
        ],
        fx: [
          { validator: validateFx, trigger: 'blur' }
        ]
      },
      editFormRules: {
        func: [
          { required: true, message: this.$t('custom.component.columns.pleaseselect'), trigger: 'change' }
        ],
        separator: [
          { required: true, message: this.$t('custom.component.columns.inuptseparator'), trigger: 'change', pattern: '[^ \x22]+' }
        ],
        field: [
          { required: true, message: this.$t('custom.component.columns.pleaseselect'), trigger: 'change' }
        ],
        alias: [
          { required: true, message: this.$t('custom.component.columns.inputalias'), trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: validateEdit, trigger: 'blur' }
        ],
        fx: [
          { validator: validateFx, trigger: 'blur' }
        ]
      },
      summarizeList: [{
        value: 'sum',
        label: 'sum'
      },
      {
        value: 'count',
        label: 'count'
      },
      {
        value: 'avg',
        label: 'avg'
      },
      {
        value: 'max',
        label: 'max'
      },
      {
        value: 'min',
        label: 'min'
      },
      {
        value: 'string_agg',
        label: 'string_agg'
      }
      ],
      addVisible: false
    }
  },

  computed: {
    formatTypeItemList () {
      let temp = []
      if(this.newSummarizeBy){
        switch (this.newSummarizeBy.businessType) {
          case 'date':
            temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_date').dataList
            break
          case 'datetime':
            temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_datetime').dataList
            break
          case 'text':
            temp = []
            break
          case 'boolean':
            temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_boolean').dataList
            break
          case 'currency':
            temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_currency').dataList
            break
          case 'number':
            temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list_number').dataList
            break
          default:
            break
      }
    }
      return temp
    },
    formatTypeList () {
      return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list').dataList.filter(item => item.dictValue !== 'hyperlinks')
    }
  },
  watch: {
    newSummarizeBy: {
      handler (val) {
        if (val.field) {
          var res = this.columnList.find(item => item.columnName === val.field)
          val.fieldAlias = res.alias
        }
      },
      deep: true
    },
    'columnList': {
      handler (val) {
        try {
          this.dataInfoCopy.measures.forEach(item => {
            var result = val.find(i => i.columnName === item.field)
            item.fieldAlias = result.alias
          })
          var res = val.find(item => item.columnName === this.newSummarizeBy.field)
          this.newSummarizeBy.fieldAlias = res.alias
          // this.columnList = JSON.parse(JSON.stringify(val))
          this.columnList.forEach((item, index) => {
            if (!item.alias || item.alias.trim() === '') {
              this.columnList.splice(index, 1)
            }
          })
        } catch (error) {
          return []
        }
      },
      deep: true
    },
    'dataInfoCopy.measures': {
      handler (val) {
        try {
          val.forEach(item => {
            if (this.errorFieldsList && this.errorFieldsList.length > 0) {
              let findIndex = this.errorFieldsList.findIndex(e => e.columnName === item.field && e.refLocation === 'widgetBuild_dataset_measure')
              if (findIndex > -1) {
                item.fieldStatus = true
              }
            } else {
              delete item.fieldStatus
            }
          })
        } catch (error) {
          return []
        }
      },
      immediate: true,
      deep: true
    }

  },
  methods: {
    rowClass (row, index) {
      if (row.fieldStatus) {
        return '#FEF0F0'
      }
    },
    handleCommand (command) {
      if (command === 'ConnectWise Ticket URL' || command === 'ConnectWise TimeEntry URL' || command === 'AutoTask Ticket URL') {
        this.newFieldsFormat = command
      } else {
        if (!this.newFieldsFormat) {
          this.newFieldsFormat = ''
        }
        this.newFieldsFormat += command
      }
    },
    openedHandler () {
      if (this.$refs.NumberFormat) {
        this.$refs.NumberFormat.open()
      }
    },
    editOpenedHandler () {
      if (this.$refs.NumberFormatEdit && this.$refs.NumberFormatEdit[this.SummarizeByEditIndex]) {
        this.$refs.NumberFormatEdit[this.SummarizeByEditIndex].open()
      }
    },
    returnSummarizeList () {
      try {
        return this.dataInfoCopy.measures
      } catch (error) {
        return []
      }
    },
    newAdvance (val) {
      if (!val) {
        this.newSummarizeBy.func = ''
        this.newSummarizeBy.separator = ''
        this.newSummarizeBy.field = ''
        this.newSummarizeBy.fieldAlias = ''
        this.newSummarizeBy.dbType = ''
      }
      this.newSummarizeBy.advanced = !val
    },
    advancedChange (val) {
      if (val) {
        this.newSummarizeBy.fx = ''
      }
      this.newSummarizeBy.advanced = !val
      this.$forceUpdate()
    },
    editSummarizeChange () {
      if (this.$refs.formatPopover) {
        this.$refs.formatPopover.doClose()
      }
      if (this.$refs.editFormatPopover && this.$refs.editFormatPopover[this.SummarizeByEditIndex]) {
        this.$refs.editFormatPopover[this.SummarizeByEditIndex].doClose()
      }
      this.newSummarizeBy.fieldsFormat = ''
      this.newSummarizeBy.fieldsNewFormat = {
        fieldsNewFormatType: 'number',
        decimals: 0,
        option: 'regular'
      }
      this.newFieldsFormat = ''
      if (this.newSummarizeBy.businessType === 'datetime') {
        this.newSummarizeBy.fieldsFormat = 'YYYY-MM-DD HH:mm'
      } else if (this.newSummarizeBy.businessType === 'date') {
        this.newSummarizeBy.fieldsFormat = 'YYYY-MM-DD'
      }
    },
    addorEditFormatShow () {
      if (this.$refs.NumberFormat) {
        this.$refs.NumberFormat.open()
      }
      this.newFieldsFormat = this.newSummarizeBy.fieldsFormat
    },
    closeEditFormat () {
      this.$refs.editFormatPopover[this.SummarizeByEditIndex].doClose()
    },
    editFormat () {
      if (this.$refs.NumberFormatEdit && this.$refs.NumberFormatEdit[this.SummarizeByEditIndex]) {
        this.$refs.NumberFormatEdit[this.SummarizeByEditIndex].open()
      }
      this.newFieldsFormat = this.newSummarizeBy.fieldsFormat
    },
    resetFormatType () {
      this.$refs.formatPopover.doClose()
      this.newFieldsFormat = ''
    },
    closeFormatPopover () {
      this.$refs.formatPopover.doClose()
      this.resetFormatType()
    },
    saveEditFormatPopover () {
      if (this.$refs.NumberFormatEdit && this.$refs.NumberFormatEdit[this.SummarizeByEditIndex]) {
        this.newSummarizeBy.fieldsNewFormat = this.$refs.NumberFormatEdit[this.SummarizeByEditIndex].save().fieldsNewFormat
      }
      this.newSummarizeBy.fieldsFormat = this.newFieldsFormat
      this.$refs.editFormatPopover[this.SummarizeByEditIndex].doClose()
    },
    saveFormatPopover () {
      if (this.$refs.NumberFormat) {
        var formatDataInfo = this.$refs.NumberFormat.save()
        this.newSummarizeBy.fieldsNewFormat = formatDataInfo.fieldsNewFormat
      }
      this.newSummarizeBy.fieldsFormat = this.newFieldsFormat
      this.$refs.formatPopover.doClose()
    },

    deleteSummarizeBy (val) {
      this.dataInfoCopy.measures.splice(val, 1)
      this.$emit('setOrderbyList')
      this.$forceUpdate()
      // this.updateReportColumn()
    },

    // TIP Optimization and handling pop-ups are not closed
    handleCloseSummarizeEditPopover () {
      if (this.SummarizeByEditIndex !== '') {
        this.dataInfoCopy.measures[this.SummarizeByEditIndex].editVisible = false
        this.SummarizeByEditIndex = ''
        this.newSummarizeBy = {
          func: '',
          separator: '',
          alias: '',
          field: '',
          fieldAlias: '',
          businessType: '',
          fieldsFormat: '',
          fieldsNewFormat: {
            fieldsNewFormatType: 'number',
            decimals: 0,
            option: 'regular'
          },
          distinct: false,
          dbType: '',
          advanced: false,
          fx: '',
          isNewPage: false,
          editVisible: false
        }
      }
    },
    handleOpenSummarizeEditPopover (item, index) {
      if (this.$refs['editForm'][this.SummarizeByEditIndex]) {
        this.$refs['editForm'][this.SummarizeByEditIndex].clearValidate()
      }
      this.handleCloseSummarizeEditPopover()
      this.handleCloseSummarizeAddPopover()

      this.newSummarizeBy = { ...JSON.parse(JSON.stringify(item)), editVisible: true }

      this.SummarizeByEditIndex = index

      this.dataInfoCopy.measures[this.SummarizeByEditIndex].editVisible = true
    },
    handleLeaveSummarizeEditPopover () {
      if (this.$refs['editForm'][this.SummarizeByEditIndex]) {
        this.$refs['editForm'][this.SummarizeByEditIndex].clearValidate()
      }
    },

    handleOpenSummarizeAddPopover () {
      if (this.$refs['summarizebyElForm']) {
        this.$refs['summarizebyElForm'].clearValidate()
      }
      this.handleCloseSummarizeEditPopover()
      this.handleCloseSummarizeAddPopover()

      this.addVisible = true
    },
    handleCloseSummarizeAddPopover () {
      if (this.addVisible) {
        this.addVisible = false
        this.newSummarizeBy = {
          func: '',
          separator: '',
          alias: '',
          field: '',
          fieldAlias: '',
          businessType: '',
          fieldsFormat: '',
          fieldsNewFormat: {
            fieldsNewFormatType: 'number',
            decimals: 0,
            option: 'regular'
          },
          distinct: false,
          dbType: '',
          advanced: false,
          fx: '',
          isNewPage: false,
          editVisible: false
        }
      }
    },
    handleLeaveSummarizeAddPopover () {
      if (this.$refs['summarizebyElForm']) {
        this.$refs['summarizebyElForm'].clearValidate()
      }
    },
    closeSummarizeby () {
      this.handleCloseSummarizeAddPopover()
      this.handleCloseSummarizeEditPopover()
    },

    addSummarizeby () {
      if (isIncludeDot(this.newSummarizeBy.alias)) {
        return this.$message.error(this.$t('validate.isIncludeDot'))
      }
      this.$refs['summarizebyElForm'].validate(isPass => {
        var _self = this
        if (isPass) {
          if (!Array.isArray(_self.dataInfoCopy.measures)) {
            _self.dataInfoCopy.measures = []
          }
          _self.dataInfoCopy.measures.push(JSON.parse(JSON.stringify(_self.newSummarizeBy)))
          _self.handleCloseSummarizeAddPopover()
          _self.$emit('setOrderbyList')
        }
      })
    },
    confirmSummarizeby () {
      if (isIncludeDot(this.newSummarizeBy.alias)) {
        return this.$message.error(this.$t('validate.isIncludeDot'))
      }
      this.$refs['editForm'][this.SummarizeByEditIndex].validate(isPass => {
        if (isPass) {
          this.dataInfoCopy.measures[this.SummarizeByEditIndex] = JSON.parse(JSON.stringify(this.newSummarizeBy))
          this.handleCloseSummarizeEditPopover()
        }
        this.$emit('setOrderbyList')
      })
    },
    newChange () {
      if (this.newSummarizeBy.func && this.newSummarizeBy.field) {
        this.newSummarizeBy.alias = this.newSummarizeBy.func + '_' + this.newSummarizeBy.field
      }
      if (this.newSummarizeBy.businessType) {
        this.newSummarizeBy.businessType = ''
        this.newSummarizeBy.fieldsFormat = ''
        this.newSummarizeBy.fieldsFormat = {
          fieldsNewFormatType: 'number',
          decimals: 0,
          option: ''
        }
        this.newSummarizeBy.distinct = false
      }
      let result = this.columnList.find(item => {
        return item.columnName === this.newSummarizeBy.field
      })
      this.newSummarizeBy.dbType = result ? result.dbType : ''
      if (this.$refs.formatPopover) {
        this.$refs.formatPopover.doClose()
      }
      if (this.$refs.editFormatPopover && this.$refs.editFormatPopover[this.SummarizeByEditIndex]) {
        this.$refs.editFormatPopover[this.SummarizeByEditIndex].doClose()
      }
    },
    clearSummarizeBy () {
      this.dataInfoCopy.measures = []
    }
  }
}
</script>
<style lang="scss">
.el-form,
.groupby-popover {
  .el-divider,
  .el-divider--horizontal {
    margin: 10px 0 !important;
  }
}
</style>
<style scoped>
.el-dropdown-menu {
  width: 400px;
  max-height: 250px;
  overflow-y: scroll;
  padding: 20px;
}
.dropDownTitle {
  display: block;
  height: 36px;
  line-height: 36px;
  font-size: 12px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.5);
}

.pop_title{
  word-break: keep-all;
  text-align: left;
}
</style>
